package org.demo.warehouse.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zgc
 * @since 2021-12-16
 */
public class R extends HashMap<String, Object> {

    private static final String OK = "200";
    private static final String FAILED = "500";
    private static final String BUSINESS_FAILED = "550";
    /**
     * 未登录
     */
    private static final String UN_AUTHENTICATION = "501";

    private R(String code, String message) {
        this(code, message, new HashMap<>(0));
    }

    private R(String code, String message, String dataKey, Object dataValue) {
        super(3);
        this.put("code", code);
        this.put("message", message);
        this.put(dataKey, dataValue);
    }

    private R(String code, String message, Map<String, Object> data) {
        super(data.size() + 2);
        this.put("code", code);
        this.put("message", message);
        this.putAll(data);
    }

    public static R ok() {
        return new R(R.OK, "成功");
    }

    public static <T> R ok(IPage<T> page) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("rows", page.getRecords());
        data.put("total", page.getTotal());
        return new R(R.OK, "成功", "data", data);
    }

    public static R ok(Object value) {
        return new R(R.OK, "成功",
                "data", value);
    }

    public static R ok(String key, Object value) {
        return new R(R.OK, "成功", key, value);
    }

    public static R ok(String message, String key, Object value) {
        return new R(R.OK, message, key, value);
    }

    public static R failed() {
        return new R(R.FAILED, "操作失败");
    }

    public static R failed(String message) {
        return new R(R.FAILED, message);
    }

    public static R failed(String message, String dataKey, Object dataValue) {
        return new R(R.FAILED, message, dataKey, dataValue);
    }

    public static R businessFailed(String message) {
        return new R(R.BUSINESS_FAILED, message);
    }

    public static R unAuthentication(String message) {
        return new R(R.UN_AUTHENTICATION, message);
    }

}

